# Flutter intl 國際化

目標:

  1. 只使用 官方的flutter_localizations,不使用其他Library 減少升級時不支援的風險
  2. 每個語言用一個arbjson, 存放翻譯的文本

網上很多教學都是教long1eu (opens new window)/flutter_i18n (opens new window)

這是一個Android Studio的插件, 幫助用戶自動生成相應的配置檔案,但作者已停止更新了。

Flutter-国际化适配终结者 (opens new window)

讓 Flutter App 支援多國語系的開發流程


研究時找到另一個相似的插件,記錄一下

FunFlutter系列之国际化Intl方案 (opens new window)

首先在Android Stuido 安裝Flutter intl (opens new window)插件

image-20200606090251399

pubspec.yaml加入官方的flutter_localizations依賴

dependencies:
    // Other dependencies...
    flutter_localizations:
        sdk: flutter
flutter pub get

點擊Initialize for the Project

image-20200606090620597

Initialize 生成配置的文件, 預設是en, 當我們修改l10n目錄下的語言檔案時會自動觸發flutter pub global run intl_utils:generate 生成generated目錄下的檔案。

image-20200606093420550

增加語言, 我加入了繁體中文zh_Hant

Locale code 參考: https://api.flutter.dev/flutter/flutter_localizations/flutter_localizations-library.html

image-20200606095646077

main.dart 加入

import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';

class MyApp extends StatelessWidget {
    
    Widget build(BuildContext context) {
        return new MaterialApp(
            localizationsDelegates: [
                S.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
            ], //add
            supportedLocales: S.delegate.supportedLocales, // add
            title: 'Flutter Demo',
            home: new MyHomePage(title: 'Flutter Demo Home Page'),
        );
    }
}

intl_en.arb, intl_zh_Hant.arb 分別加入 apple 的文本

intl_en.arb

{
  "apple": "apple"
}

intl_zh_Hant.arb

{
  "apple": "蘋果"
}

儲存後自動觸發flutter pub global run intl_utils:generate

image-20200606101934499

會根據arb檔案自動生成相對應的配置

image-20200606102019818

iOS 需要加入語言

image-20200606102326805


image-20200606103924812

Last Updated: Tue May 18 2021 13:03:26 GMT+0000
贊助商連結
(adsbygoogle = window.adsbygoogle || []).push({});